package servlet;

import db.DB;
import model.sale_list_good;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/addslistgood")//访问的时候给一个地址,高于3.0版本的包才能这么配地址
public class addslistgood extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("content-type","text/html;charset=utf-8");
        int plistid=Integer.parseInt(req.getParameter("addplistgood"));
        int goodid=Integer.parseInt(req.getParameter("addplistgoodname"));
        int amount=Integer.parseInt(req.getParameter("addplistgoodamount"));


        sale_list_good plg=new sale_list_good();
        plg.setSale_List_id(plistid);
        plg.setGoods_id(goodid);
        plg.setSale_quantity(amount);


        HttpSession session=req.getSession();

        DB DB =new DB();

        int num=DB.checkstock(goodid)-amount;

        if(num>=0){//检查库存是否足够
            DB.addslistgood(plg);
            new DB().changestock(goodid,amount*(-1));//添加订单同时修改库存
            new DB().updateslist(plistid);//同时更新订单价格
        }
        else{
            String message = "添加失败！可能原因：库存不足或商品已存在";
            session.setAttribute("message",message);
        }
        if(Integer.parseInt(req.getParameter("whichpage"))==2){
            session.setAttribute("salepage","showlist2");
        }
        else{
            session.setAttribute("salepage","createlist2");
        }
        resp.sendRedirect("salesystem.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp); }
}

